<?php

namespace LowCode\Core;

use BadMethodCallException;
use Smarty\Exception;
use Smarty\Smarty;

/**
 */
class View extends Smarty
{
    private static View $instance;

    public function __construct($directory = null)
    {
        parent::__construct();
        $config = Admin::getConfig("smarty");
        $compile_dir = $config['compile_dir']??"";
        $cache_dir = $config['cache_dir']??"";
        if ($compile_dir){
            $this->setCompileDir(getPublicPath($compile_dir));
        }
        if ($cache_dir){
            $this->setCacheDir(getPublicPath($cache_dir));
        }
        if ($directory) $this->setTemplateDir($directory);
    }

    /**
     * @param $template
     * @param array $data
     * @return string
     * @throws Exception
     */
    public function render($template, array $data = []): string
    {
        return $this->assign($data)->fetch($template);
    }

    public static function factory($directory = null): View
    {
        if (!isset(self::$instance) || !(self::$instance instanceof self)) {
            self::$instance = new self($directory);
        }else{
            self::$instance->setTemplateDir($directory);
        }
        return self::$instance;
    }
}
